<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Menus &amp; toolbars in Java SWT</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="GUI, SWT, menus, toolbars, Java, programming, linux">
<meta name="description" content="In this part of the Java SWT tutorial, we work with
menus &amp; toolbars.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container2">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content2">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Menus &amp; toolbars</h1>

<p>
In this part of the Java SWT tutorial, we will work with menus &amp; toolbars.
</p>

<div class="big_hor">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* big_horizontal */
google_ad_slot = "2904953388";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<p>
A <b>menubar</b> is one of the most common parts of the GUI application. It is a group of commands 
located in various menus.
While in console applications you have to remember all those arcane commands, 
here we have most of the commands grouped into logical parts. These are accepted standards 
that further reduce the amount of time spending to learn a new application. 
</p>


<h2>Simple menu</h2>

<p>
In our first example, we will create a menubar with one file menu. 
The menu will have only one menu item. By selecting the item the application quits. 
</p>


<pre class="code">
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * This program creates a simple menu
 * 
 * @author jan bodnar
 * website zetcode.com
 * last modified June 2009
 */

public class SWTApp {

    private Shell shell;

    public SWTApp(Display display) {

        shell = new Shell(display);

        shell.setText("Simple menu");

        initUI();

        shell.setSize(250, 200);
        shell.setLocation(300, 300);

        shell.open();

        while (!shell.isDisposed()) {
          if (!display.readAndDispatch()) {
            display.sleep();
          }
        }
    }


    public void initUI() {

        Menu menuBar = new Menu(shell, SWT.BAR);
        MenuItem cascadeFileMenu = new MenuItem(menuBar, SWT.CASCADE);
        cascadeFileMenu.setText("&amp;File");
        
        Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
        cascadeFileMenu.setMenu(fileMenu);

        MenuItem exitItem = new MenuItem(fileMenu, SWT.PUSH);
        exitItem.setText("&amp;Exit");
        shell.setMenuBar(menuBar);

        exitItem.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                shell.getDisplay().dispose();
                System.exit(0);
            }
        });

    }


    public static void main(String[] args) {
        Display display = new Display();
        new SWTApp(display);
        display.dispose();
    }
}
</pre>

<p>
This is a small example with minimal menubar functionality.
</p>

<pre class="explanation">
Menu menuBar = new Menu(shell, SWT.BAR);
</pre>

<p>
Here we create a menu bar. 
</p>

<pre class="explanation">
MenuItem cascadeFileMenu = new MenuItem(menuBar, SWT.CASCADE);
cascadeFileMenu.setText("&amp;File");
</pre>

<p>
Toplevel menu items are cascade menu items. 
</p>

<pre class="explanation">
Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
cascadeFileMenu.setMenu(fileMenu);
</pre>

<p>
We create a drop down menu. 
</p>

<pre class="explanation">
MenuItem exitItem = new MenuItem(fileMenu, SWT.PUSH);
exitItem.setText("&amp;Exit");
</pre>

<p>
A push menu item is plugged into a drop down menu. 
</p>

<pre class="explanation">
shell.setMenuBar(menuBar);
</pre>

<p>
We set a menu bar for our shell.  
</p>

<pre class="explanation">
exitItem.addSelectionListener(new SelectionAdapter() {
    @Override
    public void widgetSelected(SelectionEvent e) {
        shell.getDisplay().dispose();
        System.exit(0);
    }
});
</pre>

<p>
When we select the exit push menu item, we terminate the application.
</p>

<img src="/img/gui/swt/simplemenu.png" alt="Simple menu">
<div class="figure">Figure: Simple menu</div>


<h2>Submenu</h2>

<p>
The next example demonstrates how to create a submenu in Java SWT.
</p>

<pre class="code">
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * This program creates a submenu
 *
 * @author jan bodnar
 * website zetcode.com
 * last modified June 2009
 */

public class SWTApp {

    private Shell shell;

    public SWTApp(Display display) {

        shell = new Shell(display);

        shell.setText("Submenu");

        initUI();

        shell.setSize(250, 200);
        shell.setLocation(300, 300);

        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }

    public void initUI() {

        Menu menuBar = new Menu(shell, SWT.BAR);
        MenuItem cascadeFileMenu = new MenuItem(menuBar, SWT.CASCADE);
        cascadeFileMenu.setText("&amp;File");

        Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
        cascadeFileMenu.setMenu(fileMenu);

        MenuItem cascadeMenu = new MenuItem(menuBar, SWT.CASCADE);
        cascadeMenu.setText("&amp;File");


        MenuItem subMenuItem = new MenuItem(fileMenu, SWT.CASCADE);
        subMenuItem.setText("Import");

        Menu submenu = new Menu(shell, SWT.DROP_DOWN);
        subMenuItem.setMenu(submenu);

        MenuItem feedItem = new MenuItem(submenu, SWT.PUSH);
        feedItem.setText("&amp;Import news feed...");

        MenuItem bmarks = new MenuItem(submenu, SWT.PUSH);
        bmarks.setText("&amp;Import bookmarks...");

        MenuItem mailItem = new MenuItem(submenu, SWT.PUSH);
        mailItem.setText("&amp;Import mail...");

        MenuItem exitItem = new MenuItem(fileMenu, SWT.PUSH);
        exitItem.setText("&amp;Exit");
        shell.setMenuBar(menuBar);

        exitItem.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                shell.getDisplay().dispose();
                System.exit(0);
            }
        });

    }

    public static void main(String[] args) {
        Display display = new Display();
        new SWTApp(display);
        display.dispose();
    }
}
</pre>

<p>
Submenu creation. 
</p>

<pre class="explanation">
MenuItem subMenuItem = new MenuItem(fileMenu, SWT.CASCADE);
subMenuItem.setText("Import");
</pre>

<p>
A submenu creation is similar to creating a normal menu. First, we create a cascade menu item. 
The only difference is the parent widget. This time the parent is the menu object, to which 
the submenu belongs. 
</p>


<pre class="explanation">
MenuItem feedItem = new MenuItem(submenu, SWT.PUSH);
feedItem.setText("&amp;Import news feed...");
</pre>

<p>
We create a push menu item. The parent widget is the submenu object. 
</p>

<img src="/img/gui/swt/submenu.png" alt="Submenu">
<div class="figure">Figure: Submenu</div>


<h2>CheckMenuItem</h2>

<p>
A <code>CheckMenuItem</code> is a menu item with a check box. 
It can be used to work with boolean properties. 
</p>

<pre class="code">
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * This program creates a check menu item.
 * It will show or hide a statusbar.
 *
 * @author jan bodnar
 * website zetcode.com
 * last modified June 2009
 */

public class SWTApp {

    private Shell shell;
    private Label status;
    private MenuItem statItem;

    public SWTApp(Display display) {

        shell = new Shell(display);

        shell.setText("Check menu item");

        initUI();

        shell.setSize(300, 250);
        shell.setLocation(300, 300);

        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }
    Listener statListener = new Listener() {

        public void handleEvent(Event event) {
            if (statItem.getSelection()) {
                status.setVisible(true);
            } else {
                status.setVisible(false);
            }
        }
    };

    public void initUI() {

        Menu menuBar = new Menu(shell, SWT.BAR);
        shell.setMenuBar(menuBar);

        MenuItem cascadeFileMenu = new MenuItem(menuBar, SWT.CASCADE);
        cascadeFileMenu.setText("&amp;File");

        Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
        cascadeFileMenu.setMenu(fileMenu);


        MenuItem exitItem = new MenuItem(fileMenu, SWT.PUSH);
        exitItem.setText("&amp;Exit");

        MenuItem cascadeViewMenu = new MenuItem(menuBar, SWT.CASCADE);
        cascadeViewMenu.setText("&amp;View");

        Menu viewMenu = new Menu(shell, SWT.DROP_DOWN);
        cascadeViewMenu.setMenu(viewMenu);

        statItem = new MenuItem(viewMenu, SWT.CHECK);
        statItem.setSelection(true);
        statItem.setText("&amp;View Statusbar");

        statItem.addListener(SWT.Selection, statListener);


        exitItem.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                shell.getDisplay().dispose();
                System.exit(0);
            }
        });


        status = new Label(shell, SWT.BORDER);
        status.setText("Ready");
        FormLayout layout = new FormLayout();
        shell.setLayout(layout);

        FormData labelData = new FormData();
        labelData.left = new FormAttachment(0);
        labelData.right = new FormAttachment(100);
        labelData.bottom = new FormAttachment(100);
        status.setLayoutData(labelData);
    }

    public static void main(String[] args) {
        Display display = new Display();
        new SWTApp(display);
        display.dispose();
    }
}
</pre>

<p>
In our code example we show a check menu item. If the check box is activated,
the statusbar widget is shown. If not, the statusbar is hidden.  
</p>

<pre class="explanation">
statItem = new MenuItem(viewMenu, SWT.CHECK);
</pre>

<p>
The <code>SWT.CHECK</code> flag will create a check menu item. 
</p>

<pre class="explanation">
statItem.setSelection(true);
</pre>

<p>
The <code>setSelection()</code> method checks/unchecks the 
check menu item. 
</p>

<pre class="explanation">
if (statItem.getSelection()) {
    status.setVisible(true);
} else {
    status.setVisible(false);
}
</pre>

<p>
Depending on the state of the check menu item,
we show or hide the statusbar widget. 
</p>

<img src="/img/gui/swt/checkmenuitem.png" alt="CheckMenuItem">
<div class="figure">Figure: CheckMenuItem</div>


<h2>Popup menu</h2>

<p>
In the next example, we will create a popup menu. 
It is also called a context menu. This type of menu is shown,
when we right click on an object. 
</p>

<pre class="code">
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * This program creates a popup
 * menu
 *
 * @author jan bodnar
 * website zetcode.com
 * last modified June 2009
 */

public class SWTApp {

    private Shell shell;

    public SWTApp(Display display) {

        shell = new Shell(display);

        shell.setText("Popup menu");

        initUI();

        shell.setSize(300, 250);
        shell.setLocation(300, 300);

        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }

    public void initUI() {

        Menu menu = new Menu(shell, SWT.POP_UP);

        MenuItem minItem = new MenuItem(menu, SWT.PUSH);
        minItem.setText("Minimize");

        minItem.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                shell.setMinimized(true);
            }
        });


        MenuItem exitItem = new MenuItem(menu, SWT.PUSH);
        exitItem.setText("Exit");

        exitItem.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                shell.getDisplay().dispose();
                System.exit(0);
            }
        });

        shell.setMenu(menu);

    }

    public static void main(String[] args) {
        Display display = new Display();
        new SWTApp(display);
        display.dispose();
    }
}
</pre>

<p>
In our code example, we create a popup menu with two menu items. 
The first will minimize the window and the second will terminate
the application. 
</p>

<pre class="explanation">
Menu menu = new Menu(shell, SWT.POP_UP);
</pre>

<p>
Popup menu is created with the <code>SWT.POP_UP</code>
flag. 
</p>

<pre class="explanation">
MenuItem minItem = new MenuItem(menu, SWT.PUSH);
minItem.setText("Minimize");
</pre>

<p>
Menu items inside a popup menu are normal push menu items.  
</p>

<pre class="explanation">
public void widgetSelected(SelectionEvent e) {
    shell.setMinimized(true);
}
</pre>

<p>
This code will minimize the window. 
</p>

<pre class="explanation">
shell.setMenu(menu);
</pre>

<p>
We set a popup menu for the shell. 
</p>

<img src="/img/gui/swt/popupmenu.png" alt="Popup menu">
<div class="figure">Figure: Popup menu</div>


<h2>Simple toolbar</h2>

<p>
Menus group commands that we can use in application. 
Toolbars provide a quick access to the most frequently used commands. 
In the following example, we will create a simple toolbar. 
</p>

<pre class="code">
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;

/**
 * ZetCode Java SWT tutorial
 *
 * This program creates a simple toolbar
 *
 * @author jan bodnar
 * website zetcode.com
 * last modified June 2009
 */


public class SWTApp {

    private Shell shell;
    private Image newi;
    private Image opei;
    private Image quii;

    public SWTApp(Display display) {

        shell = new Shell(display);

        shell.setText("Simple toolbar");

        initUI();

        shell.setSize(300, 250);
        shell.setLocation(300, 300);

        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }

    public void initUI() {

        Device dev = shell.getDisplay();

        try {
            newi = new Image(dev, "new.png");
            opei = new Image(dev, "open.png");
            quii = new Image(dev, "quit.png");

        } catch (Exception e) {
            System.out.println("Cannot load images");
            System.out.println(e.getMessage());
            System.exit(1);
        }

        ToolBar toolBar = new ToolBar(shell, SWT.BORDER);

        ToolItem item1 = new ToolItem(toolBar, SWT.PUSH);
        item1.setImage(newi);

        ToolItem item2 = new ToolItem(toolBar, SWT.PUSH);
        item2.setImage(opei);

        new ToolItem(toolBar, SWT.SEPARATOR);

        ToolItem item3 = new ToolItem(toolBar, SWT.PUSH);
        item3.setImage(quii);

        toolBar.pack();

        item3.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                shell.getDisplay().dispose();
                System.exit(0);
            }
        });
    }

    public static void main(String[] args) {
        Display display = new Display();
        new SWTApp(display);
        display.dispose();
    }
}
</pre>

<p>
The example shows a toolbar and three tool items. 
</p>

<pre class="explanation">
ToolBar toolBar = new ToolBar(shell, SWT.BORDER);
</pre>

<p>
Toolbar widget is created.  
</p>

<pre class="explanation">
ToolItem item1 = new ToolItem(toolBar, SWT.PUSH);
item1.setImage(newi);
</pre>

<p>
We create a tool item with an image.   
</p>

<pre class="explanation">
new ToolItem(toolBar, SWT.SEPARATOR);
</pre>

<p>
Here we create a vertical separator. 
</p>

<img src="/img/gui/swt/toolbar.png" alt="Toolbar">
<div class="figure">Figure: Toolbar</div>

<p>
In this chapter of the Java SWT tutorial, we showed, how to work with menus &amp; toolbars.
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified June 12, 2009  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

